import {Component, OnDestroy, OnInit} from "@angular/core";
import {CommService} from "../comm-service";
import {MyhttpService} from "../myhttp.service";
import * as e from "echarts";
import {sjgzxinModuledatas} from "../pubcomponent/pageTitle.datas";

declare var $: any;

@Component({
  template: `
  <div class="all_bg">
    <div class="">
      <div class="marginBottom">
        <ng-container *ngIf="actionobj1.length">
          <portlet-action class="actions" [o]="actionobj1" (outhander)="actionHander($event)"></portlet-action>
        </ng-container>
      </div>
      <div class="portlet-body">
        <div class="row">
          <form class="form-horizontal" role="form">
            <div class="col-lg-4 col-lg-offset-2">
              <div class="form-group">
                <label class="control-label col-lg-3">标签ID:</label>
                <div class="col-lg-8">
                  <select id="sbqidSelect" data-live-search="true" class="form-control" name="bqid"
                          [(ngModel)]="s_obj.id"></select>
                </div>
              </div>
            </div>
            <div class="col-lg-4">
              <div class="form-group">
                <label class="control-label col-lg-3">时间：</label>
                <div class="col-lg-8">
                  <div class="input-group">
                    <select id="bDate" (change)="dateChange('b')"></select>
                    <span class="input-group-addon" style="width: 0.1%">至</span>
                    <select id="eDate" (change)="dateChange('e')"></select>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-lg-2">
              <button type="button" class="btn blue" (click)="getdata()">
                <i class="fa fa-search"></i> 搜索
              </button>
              &nbsp;&nbsp;
              <button type="button" class="btn default" (click)="createSearchForm('refresh')">
                重置
              </button>
            </div>
          </form>
        </div>
        <div class="row" style="margin-top: 10px;border-top: 1px solid #ccc">
          <div id="chartId"></div>
        </div>
      </div>
    </div>


    <div class="modal fad" id="lineChartModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
      <div class="modal-dialog bigmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">标签电量统计</h4>
          </div>
          <div class="modal-body">
            <div class="row">
              <div class="col-lg-12">
                <div id="chartId2"></div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" data-dismiss="modal">确 定</button>
          </div>
        </div>
      </div>
    </div>
    </div>
  `,
  styles: [
    "#chartId{width: 100%;height: 500px;margin-top: 20px}",
    "#chartId2{width: 100%;height: 450px}",
  ]
})
export class DlDzbqComponent implements OnInit, OnDestroy {
  actionobj1: any[] = [{
    pfrom: "dlbq_chart",
    title: "按月导出",
    type: "export",
    show: true
  }, {
    pfrom: "dlbq_chart",
    title: "按天导出",
    type: "dc",
    show: true
  }];
  s_obj: any = {
    id: "",
    kssj: "",
    jssj: "",
    fzlx: "month"
  };
  s_objinitid: string = "";
  dc_obj: any = {
    fzlx: "",
    kssj: "",
    jssj: ""
  }
  searchTimeRangeMax: number = 12;
  chart: any;
  chart2: any;

  /**
   * 按钮的处理回调
   * @param e
   */
  actionHander(e: any): void {
    const fromv = e.pfrom;
    const actiontype = e.type;
    if (fromv === "dlbq_chart") {
      if (actiontype === "export") {
        // 按月导出
        this.exportExcel('month');
      } else if (actiontype === "dc") {
        // 按天导出
        this.exportExcel('day');
      }
    }
  }

  exportExcel(fzlx: string): void {
    let dcreqobj;
    if (fzlx == "day") {
      const beDate = this.commservice.beDateBydate(new Date(this.commservice.convertTimeToInt(`${this.s_obj.kssj}-01 00:00:00`)));
      const kssjv = this.commservice.YMD_get(beDate[0]);
      const eDate = this.commservice.beDateBydate(new Date(this.commservice.convertTimeToInt(`${this.s_obj.jssj}-01 00:00:00`)));
      const jssjv = this.commservice.YMD_get(eDate[1]);
      dcreqobj = {
        fzlx: "day",
        kssj: kssjv, //yyyy-mm-d
        jssj: jssjv //yyyy-mm-d
      }
    } else {
      this.dc_obj.fzlx = fzlx;
      dcreqobj = Object.assign({}, this.dc_obj);
    }
    this.commservice.blockUI({
      boxed: true,
      message: "导出中...",
      zIndex: 10051,
      overlayColor: "#67809F"
    });
    const url = "sjgz/sbwb/dcbqdlExcel";
    this.itservice.kwPtPost(url, dcreqobj).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const url = resp ? resp.dcwjlj : "";
            if (url) {
              this.commservice.downFile(url, "", "");
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        }
      });
    })
  }

  getdata(): void {
    if (!this.s_obj.id) {
      return
    }
    const b1 = $("#bDate").selectpicker("val");
    const e1 = $("#eDate").selectpicker("val");
    this.s_obj.kssj = b1;
    this.s_obj.jssj = e1;
    this.dc_obj.kssj = b1;
    this.dc_obj.jssj = e1;
    const url = "sjgz/sbwb/bqdltj";
    this.itservice.kwPtPost(url, this.s_obj).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const bqdltjList = resp.bqdltjList;
            if (bqdltjList && bqdltjList.length) {
              const xAixs_items: any[] = [];
              const items_data_lydl: any[] = []; // 蓝牙电量
              const items_data_gnssdl: any[] = []; // gnssdl 电量
              bqdltjList.forEach((item) => {
                const fzsjv = item.fzsj;  // 分组时间
                const lydlv = item.lydl; // 蓝牙电量
                const gnssdlv = item.gnssdl; // gnss电量
                xAixs_items.push(fzsjv);
                items_data_lydl.push(lydlv ? Number(lydlv) : 0);
                items_data_gnssdl.push(gnssdlv ? Number(gnssdlv) : 0);
              });
              this.initChart_month(xAixs_items, items_data_lydl, items_data_gnssdl);
            }
          }
        } else {
          this.getdata();
        }
      });
    });
  }

  /**
   *month--月视图
   * @param {string[]} items
   * @param {number[]} lydldata
   * @param {number[]} gnssdldata
   */
  initChart_month(items: string[], lydldata: number[], gnssdldata: number[]): void {
    if (this.chart) {
      this.chart.clear();
    } else {
      this.chart = e.init(document.getElementById('chartId') as HTMLDivElement);
    }
    const option = this.getOption(false, items, lydldata, gnssdldata);
    this.chart.setOption(option);
    this.chart.getZr().on("click", (params) => {
      const pointInPixel = [params.offsetX, params.offsetY];
      // 使用 convertFromPixel方法 转换像素坐标值到逻辑坐标系上的点。获取点击位置对应的x轴数据的索引		 值，借助于索引值的获取到其它的信息
      const pointInGrid = this.chart.convertFromPixel({seriesIndex: 0}, pointInPixel);
      const xIndex = pointInGrid[0];
      const yAixsv = pointInGrid[1];
      if (xIndex >= 0 && yAixsv <= 100) {
        const labelDate = items[Math.abs(xIndex)];
        this.getdata_DAY(labelDate);
      }
    });
  }

  /**
   *
   *day---天视图
   * @param {string[]} items
   * @param {number[]} lydldata
   * @param {number[]} gnssdldata
   */
  initChart_day(labelDate: string, items: string[], lydldata: number[], gnssdldata: number[]): void {
    if (this.chart2) {
      this.chart2.clear();
    } else {
      this.chart2 = e.init(document.getElementById('chartId2') as HTMLDivElement);
    }
    const option = this.getOption(labelDate, items, lydldata, gnssdldata);
    this.chart2.setOption(option);
  }


  getOption(clicklabelDate: any, items: string[], lydldata: number[], gnssdldata: number[]): any {
    const option = {
      title: {
        text: "标签电量剩余情况",
        subtext: "",
        textStyle: {
          height: 50,
          lineHeight: 50
        },
        subtextStyle: {
          color: "#1477F3",
          fontSize: 15
        },
        left: "center",
        top: "top"
      },
      tooltip: {
        trigger: 'axis',
        // formatter: '{b}<br/>{a0}: {c0}%<br />{a1}: {c1}%'
      },
      legend: {
        left: "center",
        top: "bottom",
        itemWidth: 20,
        itemHeight: 10,
        itemGap: 25,
        icon: "rect",
        textStyle: {
          color: "#CFD4D9",
          fontSize: 18
        }
      },
      toolbox: {
        show: true,
        feature: {
          dataView: {readOnly: false},
          magicType: {type: ['line', 'bar']},
          restore: {},
          saveAsImage: {}
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '20%',
        top: "20%",
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: items,
        axisLine: {
          lineStyle: {
            color: '#000'
          }
        },
        axisLabel: {
          fontSize: 15,
          color: "#000"
        },
        axisTick: {
          show: false,
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        // splitNumber: 4,
        name: "电量(百分比)",
        axisLine: {
          lineStyle: {
            color: '#000'
          }
        },
        axisLabel: {
          fontSize: 15,
          color: "#000",
          formatter: function (v) {
            let retstr = "0";
            if (v) {
              retstr = `${v}%`;
            }
            return retstr;
          }
        },
        splitLine: {
          lineStyle: {
            color: '#ccc'
          }
        },
        axisTick: {
          show: false,
        }
      },
      series: [{
        type: 'line',
        name: "蓝牙电量(%)",
        data: lydldata,
        showSymbol: true,
        symbol: "circle",
        symbolSize: 10,
        itemStyle: {
          color: "#0ECEFF",
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: '#0ECEFF'
          }
        }
      }, {
        type: 'line',
        name: "gnss电量(%)",
        data: gnssdldata,
        showSymbol: true,
        symbol: "circle",
        symbolSize: 10,
        itemStyle: {
          color: "#F9DD82",
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: '#F9DD82'
          }
        }
      }]
    };
    if (clicklabelDate) {
      option["title"]["text"] = `标签电量剩余情况 (${clicklabelDate}) `;
    }
    return option;
  }

  /**
   * 点击的xAixs label对应的日期  yyyy-mm 格式
   * @param {string} labelDate
   */
  getdata_DAY(labelDate: string): void {
    const idv = this.s_obj.id;
    const beDate = this.commservice.beDateBydate(new Date(this.commservice.convertTimeToInt(`${labelDate}-01 00:00:00`)));
    const kssjv = this.commservice.YMD_get(beDate[0]);
    const jssjv = this.commservice.YMD_get(beDate[1]);
    const url = "sjgz/sbwb/bqdltj";
    this.itservice.kwPtPost(url, {
      id: idv,
      kssj: kssjv,
      jssj: jssjv,
      fzlx: "day"
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const bqdltjList = resp.bqdltjList;
            if (bqdltjList && bqdltjList.length) {
              const xAixs_items: any[] = [];
              const items_data_lydl: any[] = []; // 蓝牙电量
              const items_data_gnssdl: any[] = []; // gnssdl 电量
              bqdltjList.forEach((item) => {
                const fzsjv = item.fzsj;  // 分组时间
                const lydlv = item.lydl; // 蓝牙电量
                const gnssdlv = item.gnssdl; // gnss电量
                xAixs_items.push(fzsjv);
                items_data_lydl.push(lydlv ? Number(lydlv) : 0);
                items_data_gnssdl.push(gnssdlv ? Number(gnssdlv) : 0);
              });
              $("#lineChartModal").modal({
                keyboard: true,
                backdrop: "static"
              });
              this.initChart_day(labelDate, xAixs_items, items_data_lydl, items_data_gnssdl);
            } else {
              this.commservice.myswal("warning", "未统计到数据", "", "ts", null);
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getdata_DAY(labelDate)
        }
      });
    });

  }

  /**
   * 处理搜索表格
   * flag
   * init ---初始化
   * refresh---重置
   */
  createSearchForm(flag: string): void {
    const that = this;
    if (flag == "refresh") {
      $("#bDate").selectpicker("destroy");
      $("#eDate").selectpicker("destroy");
      this.s_obj.id = this.s_objinitid;
      $("#sbqidSelect").selectpicker("val", this.s_objinitid);
    } else {
      this.getbqidlist();
    }
    $("#bDate").empty();
    $("#eDate").empty();
    let str: string = "";
    const bdatelist: any[] = []; // 开始时间数据源， 最多 searchTimeRangeMax 个月
    // 规则，查询时间区间最大为  searchTimeRangeMax 个月
    for (let i = 0; i >= -this.searchTimeRangeMax; i--) {
      //12 -1
      const addMonth = this.commservice.addMonth(new Date(), i);
      const addMonth_ym = this.commservice.YM_get(addMonth, "separate");
      bdatelist.push(addMonth_ym);
      str += "<option value='" + addMonth_ym + "'>" + addMonth_ym + "</option>";
    }
    $("#bDate").append(str);
    $("#eDate").append(str);
    $("#bDate").selectpicker({
      size: 6
    });
    $("#eDate").selectpicker({
      size: 6
    });
    // 开始时间，赋值为最小
    $("#bDate").selectpicker('val', bdatelist[bdatelist.length - 1]);

  }


  getbqidlist(): void {
    const url = "sjgz/jcsj/dzbqsblb";
    this.itservice.kwPtPost(url, {
      sfglsjb: "",
      gpskgzt: "",
      ksjhbh: "",  //
      id: "",
      pageNum: 1,
      pageSize: 9999
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const dzbqsbList = resp.dzbqsbList;
            if (dzbqsbList && dzbqsbList.length) {
              $("#sbqidSelect").empty();
              let str: string = "";
              dzbqsbList.forEach((item) => {
                const value = item.id;
                const showv = `${value}【${item.dzbqbh}】`;
                str += "<option value='" + value + "'>" + showv + "</option>";
              });
              $("#sbqidSelect").append(str);
              $("#sbqidSelect").selectpicker({
                size: 5
              });
              this.s_obj.id = dzbqsbList[0].id;
              this.s_objinitid = dzbqsbList[0].id;
              this.getdata();
            } else {
              this.commservice.myswal("warning", "没有标签信息", "", "ts", null);
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getbqidlist();
        }
      });
    });
  }

  /**
   *
   * @param {string} type
   * b--- 开始时间框更改
   * e----结束时间框更改
   */
  dateChange(type: string): void {
    let itv: any; // yyyy-mm 字符串
    if (type == "b") {
      itv = $("#bDate").selectpicker("val");
      // 结束时间的数据源，最小从  itv 开始， 最大不能超过当前月
      const itvarr = itv.split("-");
      const itvDate = new Date(itvarr[0], Number(itvarr[1]) - 1, 1);
      let maxDate: any;
      const addmonthDate = this.commservice.addMonth(itvDate, this.searchTimeRangeMax);
      if (addmonthDate.getTime() > Date.now()) {
        // 结束时间数据源，应该从 itv ----当前月
        maxDate = new Date();
      } else {
        // 结束时间数据源，应该从itv ---addmonthDate
        maxDate = addmonthDate;
      }
      // 处理结束时间
      const rangeDatelist = this.commservice.rangeDays_moth(itvDate, maxDate);
      const rangeDatelist_reverse = rangeDatelist.reverse();
      $("#eDate").selectpicker("destroy");
      $("#eDate").empty();
      let str: string = "";
      rangeDatelist_reverse.forEach((datev) => {
        str += "<option value='" + datev + "'>" + datev + "</option>"
      });
      $("#eDate").append(str);
      $("#eDate").selectpicker({
        size: 6
      });
    } else if (type == "e") {
      const bdatestr = $("#bDate").selectpicker("val");
      itv = $("#eDate").selectpicker("val");
      const itvarr = itv.split("-");
      const itvDate = new Date(itvarr[0], Number(itvarr[1]) - 1, 1);
      // 开始时间的数据源， 最大从itv 开始， 最小不能小于 当前 -searchTimeRangeMax 个月
      const minDate = this.commservice.addMonth(itvDate, -this.searchTimeRangeMax);
      // 处理开始时间
      const rangeDatelist = this.commservice.rangeDays_moth(minDate, itvDate);
      const rangeDatelist_reverse = rangeDatelist.reverse();
      $("#bDate").selectpicker("destroy");
      $("#bDate").empty();
      let str: string = "";
      rangeDatelist_reverse.forEach((datev) => {
        str += "<option value='" + datev + "'>" + datev + "</option>"
      });
      $("#bDate").append(str);
      $("#bDate").selectpicker({
        size: 6
      });
      // 给开始时间赋值为，最初的开始时间（如果最初的开始时间在 此时开始时间数据源中的话）
      if (rangeDatelist_reverse.indexOf(bdatestr) != -1) {
        $("#bDate").selectpicker("val", bdatestr);
      }
    }

  }

  constructor(private commservice: CommService,
              private itservice: MyhttpService) {

  }

  ngOnInit() {
    this.createSearchForm('init');
  }

  ngOnDestroy() {

  }

}
